package likou.jindian;

/**
 * @author: Tangxz
 * @email: 1171702529@qq.com
 * @cate: 2020/11/25 10:16
 */
public class _03_03 {

    int[][] stack;
    int max;//一个栈的容量
    int cur;//当前应该存入的栈

    public _03_03(int cap) {
        this.max = cap;
        //多存一位，第0个位置存放元素个数
        stack = new int[1][max + 1];
        this.cur = 0;
    }

    public void push(int val) {
        if (max <= 0) return;
        //扩容
        if (stack[cur][0] == max) {
            int[][] tmp = new int[cur + 2][max + 1];
            //复制元素
            for (int i = 0; i <= cur; i++) {
                tmp[i] = stack[i];
            }
            this.stack = tmp;
            cur++;
        }
        stack[cur][0]++;
        stack[cur][stack[cur][0]] = val;
    }

    public int pop() {
        if (cur == 0 && stack[cur][0] == 0) return -1;
        int res = stack[cur][stack[cur][0]];
        stack[cur][0]--;
        removeStackIfEmpty(cur);
        return res;
    }

    public int popAt(int index) {
        if (index > cur || index < 0 || stack[index][0] == 0) return -1;
        int res = stack[index][stack[index][0]];
        stack[index][0]--;
        removeStackIfEmpty(index);
        return res;
    }

    private void removeStackIfEmpty(int index) {
        if (cur == 0) return;
        if (stack[index][0] == 0) {
            for (int i = index; i < cur; i++) {
                stack[i] = stack[i + 1];
            }
            cur--;
        }
    }
}
